/**
 * AI分析仪表板组件
 * 显示AI使用统计和分析洞察
 */

import React, { useState, useEffect } from 'react'
import { Button } from '../ui/Button'
import {
  BarChart,
  Bar,
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer
} from 'recharts'
import {
  Brain,
  TrendingUp,
  Activity,
  Clock,
  DollarSign,
  FileText,
  Users,
  Settings,
  RefreshCw,
  Download,
  Calendar
} from 'lucide-react'

interface AIAnalyticsDashboardProps {
  className?: string
  onRefresh?: () => void
}

interface AnalyticsData {
  // 使用统计
  totalRequests: number
  successfulRequests: number
  failedRequests: number
  averageResponseTime: number

  // 令牌使用
  totalTokensUsed: number
  totalCost: number
  tokensByProvider: Record<string, number>
  costByProvider: Record<string, number>

  // 功能使用
  usageByFeature: Record<string, number>
  usageByTimeframe: Array<{ date: string; requests: number; tokens: number }>

  // 项目统计
  activeProjects: number
  totalWords: number
  documentsCreated: number

  // 用户行为
  mostUsedFeatures: Array<{ feature: string; count: number }>
  preferredTimes: Array<{ hour: number; count: number }>
}

export const AIAnalyticsDashboard: React.FC<AIAnalyticsDashboardProps> = ({
  className = '',
  onRefresh,
}) => {
  const [data, setData] = useState<AnalyticsData | null>(null)
  const [loading, setLoading] = useState(true)
  const [selectedTimeRange, setSelectedTimeRange] = useState('7d')
  const [selectedTab, setSelectedTab] = useState('overview')

  // 模拟数据 - 在实际应用中会从后端获取
  useEffect(() => {
    loadAnalyticsData()
  }, [selectedTimeRange])

  const loadAnalyticsData = async () => {
    setLoading(true)
    try {
      // 这里应该调用后端API获取真实的分析数据
      const mockData: AnalyticsData = {
        totalRequests: 1247,
        successfulRequests: 1189,
        failedRequests: 58,
        averageResponseTime: 2340,

        totalTokensUsed: 284750,
        totalCost: 45.67,
        tokensByProvider: {
          'OpenAI GPT-4': 156230,
          'Claude-3': 98720,
          'DeepSeek': 29800,
        },
        costByProvider: {
          'OpenAI GPT-4': 34.20,
          'Claude-3': 9.12,
          'DeepSeek': 2.35,
        },

        usageByFeature: {
          '文本润色': 342,
          '内容扩写': 287,
          '翻译': 198,
          '摘要生成': 156,
          '续写内容': 143,
          '语法检查': 89,
          '格式化': 67,
        },
        usageByTimeframe: Array.from({ length: 7 }, (_, i) => ({
          date: new Date(Date.now() - (6 - i) * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          requests: Math.floor(Math.random() * 100) + 50,
          tokens: Math.floor(Math.random() * 5000) + 2000,
        })),

        activeProjects: 12,
        totalWords: 45780,
        documentsCreated: 34,

        mostUsedFeatures: [
          { feature: '文本润色', count: 342 },
          { feature: '内容扩写', count: 287 },
          { feature: '翻译', count: 198 },
          { feature: '摘要生成', count: 156 },
        ],
        preferredTimes: [
          { hour: 9, count: 145 },
          { hour: 14, count: 189 },
          { hour: 19, count: 167 },
          { hour: 21, count: 234 },
        ],
      }

      setData(mockData)
    } catch (error) {
      console.error('Failed to load analytics data:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleRefresh = () => {
    loadAnalyticsData()
    onRefresh?.()
  }

  const handleExport = () => {
    // 导出分析数据
    if (data) {
      const exportData = {
        exportDate: new Date().toISOString(),
        timeRange: selectedTimeRange,
        data,
      }

      const blob = new Blob([JSON.stringify(exportData, null, 2)], {
        type: 'application/json'
      })

      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `ai-analytics-${new Date().toISOString().split('T')[0]}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }
  }

  const COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899']

  // 成功率
  const successRate = data ? (data.successfulRequests / data.totalRequests * 100).toFixed(1) : '0'

  if (loading) {
    return (
      <div className={`ai-analytics-dashboard bg-white border border-gray-200 rounded-lg shadow-sm p-6 ${className}`}>
        <div className="flex items-center justify-center py-12">
          <RefreshCw className="h-8 w-8 animate-spin text-blue-500" />
          <span className="ml-2 text-gray-600">加载分析数据...</span>
        </div>
      </div>
    )
  }

  if (!data) {
    return (
      <div className={`ai-analytics-dashboard bg-white border border-gray-200 rounded-lg shadow-sm p-6 ${className}`}>
        <div className="text-center py-12 text-gray-500">
          <Brain className="h-12 w-12 mx-auto mb-3 text-gray-300" />
          <p>无法加载分析数据</p>
          <Button variant="outline" className="mt-3" onClick={handleRefresh}>
            重试
          </Button>
        </div>
      </div>
    )
  }

  return (
    <div className={`ai-analytics-dashboard bg-white border border-gray-200 rounded-lg shadow-sm ${className}`}>
      {/* 头部 */}
      <div className="border-b border-gray-200 p-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <Brain className="h-6 w-6 text-blue-500" />
            <div>
              <h2 className="text-xl font-semibold">AI分析仪表板</h2>
              <p className="text-sm text-gray-500">智能写作助手使用统计与分析</p>
            </div>
          </div>

          <div className="flex items-center space-x-2">
            <select
              value={selectedTimeRange}
              onChange={(e) => setSelectedTimeRange(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="24h">过去24小时</option>
              <option value="7d">过去7天</option>
              <option value="30d">过去30天</option>
              <option value="90d">过去90天</option>
            </select>

            <Button variant="outline" size="sm" onClick={handleRefresh}>
              <RefreshCw className="h-4 w-4" />
            </Button>

            <Button variant="outline" size="sm" onClick={handleExport}>
              <Download className="h-4 w-4 mr-1" />
              导出
            </Button>
          </div>
        </div>
      </div>

      {/* 标签页 */}
      <div className="border-b border-gray-200">
        <div className="flex">
          {[
            { id: 'overview', label: '概览', icon: Activity },
            { id: 'usage', label: '使用情况', icon: TrendingUp },
            { id: 'costs', label: '成本分析', icon: DollarSign },
            { id: 'features', label: '功能分析', icon: Settings },
          ].map((tab) => {
            const Icon = tab.icon
            return (
              <button
                key={tab.id}
                onClick={() => setSelectedTab(tab.id)}
                className={`px-4 py-3 border-b-2 font-medium text-sm transition-colors ${
                  selectedTab === tab.id
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700'
                }`}
              >
                <Icon className="h-4 w-4 mr-2 inline" />
                {tab.label}
              </button>
            )
          })}
        </div>
      </div>

      {/* 内容区域 */}
      <div className="p-6">
        {/* 概览标签 */}
        {selectedTab === 'overview' && (
          <div className="space-y-6">
            {/* 关键指标 */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="bg-blue-50 p-4 rounded-lg">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-blue-600">总请求数</p>
                    <p className="text-2xl font-bold text-blue-900">{data.totalRequests.toLocaleString()}</p>
                  </div>
                  <Activity className="h-8 w-8 text-blue-500" />
                </div>
              </div>

              <div className="bg-green-50 p-4 rounded-lg">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-green-600">成功率</p>
                    <p className="text-2xl font-bold text-green-900">{successRate}%</p>
                  </div>
                  <TrendingUp className="h-8 w-8 text-green-500" />
                </div>
              </div>

              <div className="bg-yellow-50 p-4 rounded-lg">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-yellow-600">平均响应时间</p>
                    <p className="text-2xl font-bold text-yellow-900">{(data.averageResponseTime / 1000).toFixed(1)}s</p>
                  </div>
                  <Clock className="h-8 w-8 text-yellow-500" />
                </div>
              </div>

              <div className="bg-purple-50 p-4 rounded-lg">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-purple-600">总消耗</p>
                    <p className="text-2xl font-bold text-purple-900">${data.totalCost.toFixed(2)}</p>
                  </div>
                  <DollarSign className="h-8 w-8 text-purple-500" />
                </div>
              </div>
            </div>

            {/* 使用趋势 */}
            <div className="bg-gray-50 p-4 rounded-lg">
              <h3 className="text-lg font-medium mb-4">使用趋势</h3>
              <ResponsiveContainer width="100%" height={200}>
                <LineChart data={data.usageByTimeframe}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Line
                    type="monotone"
                    dataKey="requests"
                    stroke="#3b82f6"
                    strokeWidth={2}
                    name="请求数"
                  />
                  <Line
                    type="monotone"
                    dataKey="tokens"
                    stroke="#10b981"
                    strokeWidth={2}
                    name="令牌数"
                  />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </div>
        )}

        {/* 使用情况标签 */}
        {selectedTab === 'usage' && (
          <div className="space-y-6">
            {/* 功能使用分布 */}
            <div>
              <h3 className="text-lg font-medium mb-4">功能使用分布</h3>
              <ResponsiveContainer width="100%" height={300}>
                <PieChart>
                  <Pie
                    data={Object.entries(data.usageByFeature).map(([name, value]) => ({
                      name,
                      value,
                    }))}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {Object.entries(data.usageByFeature).map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </div>

            {/* 最常用功能 */}
            <div>
              <h3 className="text-lg font-medium mb-4">最常用功能</h3>
              <div className="space-y-2">
                {data.mostUsedFeatures.map((feature, index) => (
                  <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded">
                    <span className="font-medium">{feature.feature}</span>
                    <span className="text-sm text-gray-600">{feature.count} 次</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* 成本分析标签 */}
        {selectedTab === 'costs' && (
          <div className="space-y-6">
            {/* 供应商成本分布 */}
            <div>
              <h3 className="text-lg font-medium mb-4">供应商成本分布</h3>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={Object.entries(data.costByProvider).map(([name, value]) => ({
                  name,
                  cost: value,
                }))}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <Tooltip />
                  <Bar dataKey="cost" fill="#3b82f6" />
                </BarChart>
              </ResponsiveContainer>
            </div>

            {/* 令牌使用统计 */}
            <div>
              <h3 className="text-lg font-medium mb-4">令牌使用统计</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="bg-gray-50 p-4 rounded-lg">
                  <p className="text-sm text-gray-600">总令牌使用</p>
                  <p className="text-xl font-bold">{data.totalTokensUsed.toLocaleString()}</p>
                </div>
                <div className="bg-gray-50 p-4 rounded-lg">
                  <p className="text-sm text-gray-600">每请求平均令牌</p>
                  <p className="text-xl font-bold">
                    {Math.round(data.totalTokensUsed / data.totalRequests)}
                  </p>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 功能分析标签 */}
        {selectedTab === 'features' && (
          <div className="space-y-6">
            {/* 项目统计 */}
            <div>
              <h3 className="text-lg font-medium mb-4">项目统计</h3>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="bg-gray-50 p-4 rounded-lg">
                  <div className="flex items-center space-x-2">
                    <FileText className="h-5 w-5 text-blue-500" />
                    <div>
                      <p className="text-sm text-gray-600">活跃项目</p>
                      <p className="text-xl font-bold">{data.activeProjects}</p>
                    </div>
                  </div>
                </div>
                <div className="bg-gray-50 p-4 rounded-lg">
                  <div className="flex items-center space-x-2">
                    <Users className="h-5 w-5 text-green-500" />
                    <div>
                      <p className="text-sm text-gray-600">总字数</p>
                      <p className="text-xl font-bold">{data.totalWords.toLocaleString()}</p>
                    </div>
                  </div>
                </div>
                <div className="bg-gray-50 p-4 rounded-lg">
                  <div className="flex items-center space-x-2">
                    <FileText className="h-5 w-5 text-purple-500" />
                    <div>
                      <p className="text-sm text-gray-600">创建文档</p>
                      <p className="text-xl font-bold">{data.documentsCreated}</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}